# -*- coding: utf-8 -*-
'''
Created on 2009-04-13

@author: argaz
'''

import tkMessageBox as msgBox
import sys

try:
    from xTkinter import *
except:
    print >> sys.stderr, 'Le module xTkinter est  introuvable'  
    sys.exit(1)

class VueCreationTable(Frame):
    ListeTables=[]
    ListeChamps=[]
    def __init__(self,master,parent,**cnf):
        Frame.__init__(self,master,cnf)
        KeysList=cnf.keys()
        self.parent = parent
        self.master=master
        self.table=None
        self.listeChamps=[]
        if ('width' in KeysList):
            self.width=cnf['width']
        if ('width' in KeysList):
            self.height=cnf['height']
        Frame.__init__(self,master,cnf)          
        self.pack(side=LEFT,anchor=NW)
        """
        Variable qui va servir a determiner si les donnees d'un
        champs ont ete modifies par l'utilisateur
        """
        self.champtampon=None
        
        self.configure(width=800,height=600)
        LTable=xLabel(self,text='Table a  creer',height=1,width=15)
        LTable.setLocation(10,10)
        self.ETable=xEntry(self,width=15)
        self.ETable.setLocation(80,10)       
        "  Liste des tables existantes "
        LListeTables=xLabel(self,text='Tables existantes',height=1,width=15)
        LListeTables.setLocation(210,10)
        self.CBListeTables=xCombobox(self,width=10)
        self.CBListeTables.setLocation(310,10)
        self.CBListeTables.setListWidth(15) 
        self.CBListeTables.setListHeight(3)       
        self.CBListeTables.setText('<aucune>')
        self.TableSelectionne = None
        LChamps=xLabel(self,text='Champs de la table',height=1,width=18)
        LChamps.setLocation(210,40)
        self.listTables()
        " Pour recharger la liste des tables"
        RechargeTables=xButton(self,text='Creer')
        RechargeTables.setLocation(180,10)
        RechargeTables.configure(anchor=CENTER)
        RechargeTables.setCommand(self.isExist)
        
        " Liste des champs d'une table selectionnee"
        self.CBListeChamps=xCombobox(self,width=7)
        self.CBListeChamps.setLocation(310,40)
        self.CBListeChamps.setWidth(12)
        self.CBListeChamps.setText('<aucun>')
        self.CBListeChamps.setListWidth(15)
        self.CBListeChamps.setListHeight(3)
        
        TitreChamps=xLabel(self,text='Titre du champs',height=1,width=15)
        TitreChamps.setLocation(10,69)
        xLabel3=xLabel(self,text='Type du champs',height=1,width=15)
        xLabel3.setLocation(106,69)
        xLabel4=xLabel(self,text='Taille',height=1,width=6)
        xLabel4.setLocation(196,69)
        xLabel5=xLabel(self,text='Precision',height=1,width=9)
        xLabel5.setLocation(239,69)
        xLabel6=xLabel(self,text='Pattern',height=1,width=7)
        xLabel6.setLocation(300,69)
        self.ETitreChamps=xEntry(self,width=15)
        self.ETitreChamps.setLocation(10,90)
        
        " Type du champs choisi"
        self.CBTypeChamps=xCombobox(self,width=11)
        self.CBTypeChamps.setLocation(107,90)
        self.CBTypeChamps.setText('<aucun>')
        self.CBTypeChamps.setListHeight(5)
        self.CBTypeChamps.setListWidth(15)
        self.CBTypeChamps.addItems(['texte','numerique','date','caractere'])
        self.CBTypeChamps.setText('texte')
        def activeAttributs():
            if (self.CBTypeChamps.getText() in ['texte','numerique']):
                self.SBTaille.setActive(True)
                if (self.CBTypeChamps.getText() == 'numerique'):
                    self.SBPrecision.setActive(True)
            else:
                self.SBTaille.setActive(False)
                self.SBPrecision.setActive(False)
            pass
        self.CBTypeChamps.setValidator(activeAttributs)
        
        """
        Spinbutton pour changer la taille du champs 
        Fonction non encore implementee
        """
        self.SBTaille=xSpinbox(self,width=4)
        self.SBTaille.setLocation(197,90)
        self.SBTaille.setValue(10)
        self.SBPrecision=xSpinbox(self,width=7)
        self.SBPrecision.setLocation(239,90)
        self.SBPrecision.setValue(0)
        self.CBPattern=xCombobox(self,width=10)
        self.CBPattern.setLocation(300,90)
        self.CBPattern.setText('<aucun>')
        
        """
        Cette colonne est prevue pour le pattern de la date
             exp jj/mm/aaaa
        """
        xLabel6.setVisible(False)
        self.CBPattern.setVisible(False)
        self.CBPattern.setActive(False)        

        
        self.var=IntVar()
        """
        Ajouter le champs
        """

        self.BAjouter=xButton(self,text='Ajouter',width=10)
        self.BAjouter.setLocation(250,140)
        self.BAjouter.configure(anchor=CENTER)
        self.BAjouter.setCommand(self.ajouterChamps)

        self.BAjouter=xButton(self,text='Terminer',width=10)
        self.BAjouter.setLocation(330,140)
        self.BAjouter.configure(anchor=CENTER)
        self.BAjouter.setCommand(self.creerTable)
        
        #self.BValider.setActive(False)     

        " Fonction assocee a  l'evennement <Choix d'une table> "
     
        #self.CBListeTables.setValidator(self.obtenirChamps)
  
        " fonction associee a l'evennement <detail du champs>"

        #self.CBListeChamps.setValidator(self.obtenirDescriptionChamps)


    def ajouterChamps(self):
        if(self.ETitreChamps.getText().upper() in VueCreationTable.ListeChamps):
            msgBox.showerror('Creation table', 'Le champ '+\
                              self.ETitreChamps.getText()+' existe deja ')
        else:
            args={}
            args['nom']=self.ETitreChamps.getText()
            args['type']=self.CBTypeChamps.getText()
            if (args['type'] in ['texte','numerique']):
                args['taille']=self.SBTaille.getValue()
                if (args['type']=='numerique'):
                    if self.SBPrecision.getValue()>0:
                        args['precision']=self.SBPrecision.getValue()
                    else:
                        args['precision']=0
            self.CBListeChamps.addItem(args['nom'])       
            self.listeChamps.append(args)
            VueCreationTable.ListeChamps.append(self.ETitreChamps.getText().upper())
        pass
    
    def creerTable(self):
        args={}
        args['table']=self.table
        args['user']='admin'
        args['listechamps']=self.listeChamps
        self.parent.serveur.CreerTable(args)
        pass    
    
 
    def isExist(self):
        if(len(self.ETable.getText())>0):
            self.table=self.ETable.getText()
            if (self.table.upper() in VueCreationTable.ListeTables):
                msgBox.showerror('Creation table', 'La table '+ self.table+' existe dejaÂ ')
                self.ETable.setText('')
            else:
                self.CBListeTables.addItem(self.table)
                VueCreationTable.ListeTables.append(self.table.upper())
        pass
    
#    def listTables(self):
#        Reponse = self.parent.BaseDonnees.ObtenirTable()
#        if (Reponse[0]==1):
#            self.CBListeTables.clear()
#            self.CBListeTables.setListHeight(3)
#            NomsTable = Reponse[1]
#            for NomTable in NomsTable:
#                laTable=NomTable[0]
#                VueCreationTable.ListeTables.append(laTable.upper())
#                self.CBListeTables.addItem(NomTable)
#            self.CBListeTables.setSelected(0)
#            self.CBListeTables.setText('<CHOISIR>')
#            
#            
#        else:
#            msgBox.showerror('PERP 2009 | Edition des tables', 'Une erreur est survenue!\n'+Reponse[1])
#        pass
    
    def listTables(self):
        Reponse = self.parent.serveur.ObtenirListeTables(self.parent.user,self.parent.profil)
        if (Reponse[0]==1):
            self.CBListeTables.clear()
            self.CBListeTables.setListHeight(3)
            NomsTables = Reponse[1]
            for NomTable in NomsTables:
                self.CBListeTables.addItem(NomTable[0])
                VueCreationTable.ListeTables.append(NomTable[0].upper())
            self.CBListeTables.setSelected(0)
            self.CBListeTables.setText('<CHOISIR>')
        else:
            msgBox.showerror('PERP 2009 | Édition des tables', 'Une erreur est survenue!\n'+Reponse[1])
        pass   
     
    def close(self):
        self.destroy()
        pass
